<template>
	<view class="container">
		<!-- 记账表单 -->
		<view class="bill-card">
			<view class="bill-form">
				<!-- 金额输入 -->
				<view class="form-row">
					<text class="row-label">金额</text>
					<view class="row-content">
						<input class="amount-input" type="float" v-model="record.amount" placeholder="" />
					</view>
				</view>
				
				<!-- 收支类型 -->
				<view class="form-row">
					<text class="row-label">类型</text>
					<view class="row-content">
						<view class="type-selector">
							<view 
								class="type-item" 
								:class="{ active: record.type === 0 }" 
								@click="changeType(0)">
								支出
							</view>
							<view 
								class="type-item" 
								:class="{ active: record.type === 1 }" 
								@click="changeType(1)">
								收入
							</view>
						</view>
					</view>
				</view>
				
				<!-- 一级分类 -->
				<view class="form-row" @click="showCategoryPicker">
					<text class="row-label">分类</text>
					<view class="row-content">
						<text class="item-text">{{ selectedCategoryName || '请选择分类' }}</text>
					</view>
				</view>
				
				<!-- 二级分类 -->
				<view class="form-row" @click="showSubCategoryPicker" v-if="selectedCategory">
					<text class="row-label">子分类</text>
					<view class="row-content">
						<text class="item-text">{{ selectedSubCategoryName || '请选择子分类' }}</text>
					</view>
				</view>
				
				<!-- 描述 -->
				<view class="form-row">
					<text class="row-label">描述</text>
					<view class="row-content">
						<input class="desc-input" v-model="record.description" placeholder="请输入描述（可选）" />
					</view>
				</view>
				
				<!-- 日期 -->
				<view class="form-row" @click="showDatePicker">
					<text class="row-label">日期</text>
					<view class="row-content">
						<text class="item-text">{{ formatDate(record.record_date) }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 保存按钮 -->
		<view class="save-section">
			<button class="save-btn" @click="saveRecord">保存记录</button>
		</view>
		
		<!-- 分类选择器 -->
	<uni-popup ref="categoryPopup" type="bottom" :animation="false" :mask-animation="false">
			<view class="popup-container">
				<view class="popup-header">
					<text class="popup-title">选择分类</text>
					<text class="popup-close" @click="closeCategoryPopup">取消</text>
				</view>
				<scroll-view class="category-list" scroll-y>
					<view 
						class="category-item" 
						v-for="category in categories" 
						:key="category.id"
						@click="selectCategory(category)">
						<text>{{ category.name }}</text>
					</view>
					<!-- 添加空状态提示 -->
					<view v-if="!categories || categories.length === 0" class="empty-state">
						<text>暂无分类数据</text>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
		
		<!-- 子分类选择器 -->
	<uni-popup ref="subCategoryPopup" type="bottom" :animation="false" :mask-animation="false">
			<view class="popup-container">
				<view class="popup-header">
					<text class="popup-title">选择子分类</text>
					<text class="popup-close" @click="closeSubCategoryPopup">取消</text>
				</view>
				<scroll-view class="category-list" scroll-y>
					<view 
						class="category-item" 
						v-for="subCategory in subCategories" 
						:key="subCategory.id"
						@click="selectSubCategory(subCategory)">
						<text>{{ subCategory.name }}</text>
					</view>
					<!-- 添加空状态提示 -->
					<view v-if="!subCategories || subCategories.length === 0" class="empty-state">
						<text>暂无子分类数据</text>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
		
		<!-- 日期选择器 -->
	<uni-popup ref="datePopup" type="bottom" :animation="false" :mask-animation="false" mask-click="false">
			<view class="popup-container">
				<view class="popup-header">
					<text class="popup-title">选择日期</text>
					<text class="popup-close" @click="closeDatePopup">取消</text>
				</view>
				<view class="date-picker-container">
					<picker-view :value="dateValue" :key="dateValue.join('-')" @change="onDateChange" class="date-picker">
						<picker-view-column>
							<view class="picker-item" v-for="year in years" :key="year">{{ year }}年</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="month in months" :key="month">{{ month }}月</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="day in days" :key="day">{{ day }}日</view>
						</picker-view-column>
					</picker-view>
				</view>
				<view class="confirm-btn-container">
					<button class="confirm-btn" @click="confirmDate">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import config from '@/config/api.js'
	import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
	
	export default {
		components: {
			uniPopup
		},
		data() {
			return {
				record: {
					amount: '',
					type: 0, // 0-支出, 1-收入
					category_id: null,
					sub_category_id: null,
					description: '',
					record_date: new Date().toISOString().split('T')[0] // 默认今天
				},
				categories: [], // 一级分类
				subCategories: [], // 二级分类
				selectedCategory: null,
				selectedCategoryName: '',
				selectedSubCategory: null,
				selectedSubCategoryName: '',
				// 日期选择器数据
				dateValue: [0, 0, 0],
				years: [],
				months: [],
				days: [],
				tempDate: {
					year: new Date().getFullYear(),
					month: new Date().getMonth() + 1,
					day: new Date().getDate()
				}
			}
		},
		onLoad() {
			// 初始化日期选择器数据
			this.initDatePicker();
			
			// 加载分类数据
			this.loadCategories().then(() => {
				console.log('分类数据加载完成:', this.categories);
			}).catch(err => {
				console.error('分类数据加载失败:', err);
			});
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.refreshData();
		},
		watch: {
			'record.record_date'(newVal) {
				// 只要日期变更，dateValue也同步
				if (newVal) {
					const dateObj = new Date(newVal);
					const yearIndex = this.years.indexOf(dateObj.getFullYear());
					const monthIndex = this.months.indexOf(dateObj.getMonth() + 1);
					const dayIndex = this.days.indexOf(dateObj.getDate());
					this.dateValue = [
						yearIndex !== -1 ? yearIndex : 0,
						monthIndex !== -1 ? monthIndex : 0,
						dayIndex !== -1 ? dayIndex : 0
					];
				}
			}
		},
		methods: {
			// 刷新数据
			async refreshData() {
				try {
					// 清除本地缓存
					uni.removeStorageSync('billCategories');
					// 清除所有子分类缓存
					const keys = uni.getStorageInfoSync().keys;
					keys.forEach(key => {
						if (key.startsWith('billSubCategories_')) {
							uni.removeStorageSync(key);
						}
					});
					
					// 重新加载分类数据
					await this.loadCategories();
					
					uni.showToast({
						title: '刷新成功',
						icon: 'success'
					});
				} catch (e) {
					console.error('刷新数据异常', e);
					uni.showToast({
						title: '刷新失败',
						icon: 'none'
					});
				} finally {
					uni.stopPullDownRefresh();
				}
			},
			
			// 初始化日期选择器
			initDatePicker() {
				// 生成年份、月份、日期列表
				const now = new Date();
				const currentYear = now.getFullYear();
				this.years = [];
				for (let i = currentYear - 10; i <= currentYear + 10; i++) {
					this.years.push(i);
				}
				this.months = [];
				for (let i = 1; i <= 12; i++) {
					this.months.push(i);
				}
				this.days = [];
				for (let i = 1; i <= 31; i++) {
					this.days.push(i);
				}

				// 取record.record_date为基准
				let dateStr = this.record && this.record.record_date ? this.record.record_date : '';
				if (!dateStr) {
					// 如果为空，默认当天
					const month = (now.getMonth() + 1).toString().padStart(2, '0');
					const day = now.getDate().toString().padStart(2, '0');
					dateStr = `${now.getFullYear()}-${month}-${day}`;
					this.record.record_date = dateStr;
				}
				const dateObj = new Date(dateStr);
				const yearIndex = this.years.indexOf(dateObj.getFullYear());
				const monthIndex = this.months.indexOf(dateObj.getMonth() + 1);
				const dayIndex = this.days.indexOf(dateObj.getDate());
				this.dateValue = [
					yearIndex !== -1 ? yearIndex : 0,
					monthIndex !== -1 ? monthIndex : 0,
					dayIndex !== -1 ? dayIndex : 0
				];
			},
			
			// 日期选择变化
			onDateChange(e) {
				this.dateValue = e.detail.value;
				// 确保索引有效再更新tempDate
				if (this.dateValue[0] < this.years.length && 
				    this.dateValue[1] < this.months.length && 
				    this.dateValue[2] < this.days.length) {
					this.tempDate.year = this.years[this.dateValue[0]];
					this.tempDate.month = this.months[this.dateValue[1]];
					this.tempDate.day = this.days[this.dateValue[2]];
				}
			},
			
			// 确认选择日期
			confirmDate() {
				// 确保tempDate有有效值
				if (this.tempDate.year && this.tempDate.month && this.tempDate.day) {
					// 格式化日期为 YYYY-MM-DD
					const month = this.tempDate.month.toString().padStart(2, '0');
					const day = this.tempDate.day.toString().padStart(2, '0');
					this.record.record_date = `${this.tempDate.year}-${month}-${day}`;
				}
				// 关闭弹窗后同步dateValue
				const dateObj = new Date(this.record.record_date);
				const yearIndex = this.years.indexOf(dateObj.getFullYear());
				const monthIndex = this.months.indexOf(dateObj.getMonth() + 1);
				const dayIndex = this.days.indexOf(dateObj.getDate());
				this.dateValue = [
					yearIndex !== -1 ? yearIndex : 0,
					monthIndex !== -1 ? monthIndex : 0,
					dayIndex !== -1 ? dayIndex : 0
				];
				this.closeDatePopup();
			},
			
			// 格式化日期显示
			formatDate(dateString) {
				if (!dateString) return '';
				const date = new Date(dateString);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}年${month}月${day}日`;
			},
			
			// 改变收支类型
			changeType(type) {
				this.record.type = type;
			},
			
			// 显示分类选择器
			showCategoryPicker() {
				console.log('显示分类选择器，当前分类数据:', this.categories);
				if (!this.categories || this.categories.length === 0) {
					uni.showToast({
						title: '分类数据未加载',
						icon: 'none'
					});
					// 尝试重新加载
					this.loadCategories();
					return;
				}
				this.$refs.categoryPopup.open();
			},
			
			// 关闭分类选择器
			closeCategoryPopup() {
				this.$refs.categoryPopup.close();
			},
			
			// 选择一级分类
			selectCategory(category) {
				this.selectedCategory = category;
				this.selectedCategoryName = category.name;
				this.record.category_id = category.id;
				
				// 清空之前的子分类选择
				this.selectedSubCategory = null;
				this.selectedSubCategoryName = '';
				this.record.sub_category_id = null;
				
				// 加载对应的子分类
				this.loadSubCategories(category.id);
				
				this.closeCategoryPopup();
			},
			
			// 显示子分类选择器
			showSubCategoryPicker() {
				if (!this.selectedCategory) {
					uni.showToast({
						title: '请先选择分类',
						icon: 'none'
					});
					return;
				}
				this.$refs.subCategoryPopup.open();
			},
			
			// 关闭子分类选择器
			closeSubCategoryPopup() {
				this.$refs.subCategoryPopup.close();
			},
			
			// 选择二级分类
			selectSubCategory(subCategory) {
				this.selectedSubCategory = subCategory;
				this.selectedSubCategoryName = subCategory.name;
				this.record.sub_category_id = subCategory.id;
				this.closeSubCategoryPopup();
			},
			
			// 显示日期选择器
			showDatePicker() {
				// 保证years/months/days已初始化
				if (!this.years || !this.months || !this.days || this.years.length === 0 || this.months.length === 0 || this.days.length === 0) {
					this.initDatePicker();
				}

				console.log(this.dateValue);
				console.log(this.tempDate);
				
				// 强制刷新picker-view
				this.dateValue = [0, 0, 0];
				this.$nextTick(() => {
					let dateStr = this.record.record_date;
					if (!dateStr) {
						// 如果为空，默认当天
						const today = new Date();
						const month = (today.getMonth() + 1).toString().padStart(2, '0');
						const day = today.getDate().toString().padStart(2, '0');
						dateStr = `${today.getFullYear()}-${month}-${day}`;
						this.record.record_date = dateStr;
					}
					const now = new Date(dateStr);
					const currentYear = now.getFullYear();
					const currentMonth = now.getMonth() + 1; // 月份从1开始
					const currentDay = now.getDate();
					const yearIndex = this.years.indexOf(currentYear);
					const monthIndex = this.months.indexOf(currentMonth);
					const dayIndex = this.days.indexOf(currentDay);
					this.dateValue = [
						yearIndex !== -1 ? yearIndex : 0,
						monthIndex !== -1 ? monthIndex : 0,
						dayIndex !== -1 ? dayIndex : 0
					];
					// 更新tempDate
					this.tempDate.year  = currentYear;
					this.tempDate.month = currentMonth;
					this.tempDate.day   = currentDay;
					this.$refs.datePopup.open();
				});
			},
			
			// 关闭日期选择器
			closeDatePopup() {
				this.$refs.datePopup.close();
			},
			
			// 加载一级分类
			async loadCategories() {
				try {
					// 首先尝试从本地缓存获取
					const cachedCategories = uni.getStorageSync('billCategories');
					if (cachedCategories) {
						this.categories = cachedCategories;
						// 修复：确保在有缓存数据时正确返回
						if (this.categories.length > 0) {
							console.log('从缓存加载分类数据:', this.categories);
							return this.categories;
						}
					}
					
					// 如果本地没有缓存，则从服务器获取
					console.log('从服务器获取分类数据...');
					const res = await uni.request({
						url: config.baseUrl + config.api.billCategories,
						method: 'GET'
					});
					
					if (res.statusCode === 200) {
						// 修复：正确处理返回的数据结构
						this.categories = res.data.data.categories || res.data || [];
						console.log('从服务器获取到的分类数据:', res.data.data.categories);
						// 缓存到本地
						uni.setStorageSync('billCategories', this.categories);
						return this.categories;
					} else {
						console.error('获取一级分类失败', res);
						uni.showToast({
							title: '获取分类失败',
							icon: 'none'
						});
					}
				} catch (e) {
					console.error('获取一级分类异常', e);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				}
			},
			
			// 加载二级分类
			async loadSubCategories(categoryId) {
				try {
					// 首先尝试从本地缓存获取
					const cacheKey = `billSubCategories_${categoryId}`;
					const cachedSubCategories = uni.getStorageSync(cacheKey);
					if (cachedSubCategories) {
						this.subCategories = cachedSubCategories;
						console.log('从缓存加载子分类数据:', this.subCategories);
						return;
					}
					
					// 如果本地没有缓存，则从服务器获取
					console.log('从服务器获取子分类数据，分类ID:', categoryId);
					const res = await uni.request({
						url: config.baseUrl + config.api.billSubCategories,
						method: 'GET',
						data: {
							category_id: categoryId
						}
					});
					
					if (res.statusCode === 200) {
						// 修复：正确处理返回的数据结构
						this.subCategories = res.data.data.sub_categories || res.data || [];
						console.log('从服务器获取到的子分类数据:', this.subCategories);
						// 缓存到本地
						uni.setStorageSync(cacheKey, this.subCategories);
					} else {
						console.error('获取二级分类失败', res);
						uni.showToast({
							title: '获取子分类失败',
							icon: 'none'
						});
					}
				} catch (e) {
					console.error('获取二级分类异常', e);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				}
			},
			
			// 保存记录
			async saveRecord() {
				// 验证必填字段
				if (!this.record.amount) {
					uni.showToast({
						title: '请输入金额',
						icon: 'none'
					});
					return;
				}
				
				if (!this.record.category_id) {
					uni.showToast({
						title: '请选择分类',
						icon: 'none'
					});
					return;
				}
				
				// 获取用户ID
				const userInfo = uni.getStorageSync('userInfo');
				if (!userInfo || !userInfo.id) {
					uni.showToast({
						title: '用户信息异常，请重新登录',
						icon: 'none'
					});
					return;
				}
				
				const recordData = {
					...this.record,
					user_id: userInfo.id,
					amount: parseFloat(this.record.amount)
				};
				
				try {
					const res = await uni.request({
						url: config.baseUrl + config.api.records,
						method: 'POST',
						data: recordData
					});
					
					if (res.statusCode === 200 || res.statusCode === 201) {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
						
						// 清空表单
						this.resetForm();
					} else {
						console.error('保存记录失败', res);
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				} catch (e) {
					console.error('保存记录异常', e);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				}
			},
			
			// 重置表单
			resetForm() {
				this.record = {
					amount: '',
					type: 0,
					category_id: null,
					sub_category_id: null,
					description: '',
					record_date: new Date().toISOString().split('T')[0]
				};
				// 同步dateValue
				const dateObj = new Date(this.record.record_date);
				const yearIndex = this.years.indexOf(dateObj.getFullYear());
				const monthIndex = this.months.indexOf(dateObj.getMonth() + 1);
				const dayIndex = this.days.indexOf(dateObj.getDate());
				this.dateValue = [
					yearIndex !== -1 ? yearIndex : 0,
					monthIndex !== -1 ? monthIndex : 0,
					dayIndex !== -1 ? dayIndex : 0
				];
				this.selectedCategory = null;
				this.selectedCategoryName = '';
				this.selectedSubCategory = null;
				this.selectedSubCategoryName = '';
				this.subCategories = [];
			}
		}
	}
</script>

<style scoped>
	.container {
		background-color: #f8f8f8;
		min-height: 100vh;
		padding: 15rpx;
	}
	
	.bill-card {
		background-color: white;
		border-radius: 8rpx;
		padding: 20rpx;
		margin-bottom: 15rpx;
		box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
	}
	
	.form-row {
		display: flex;
		align-items: center;
		padding: 15rpx 0;
		min-height: 50rpx;
	}
	
	.form-row:last-child {
	}
	
	.row-label {
		width: 100rpx;
		font-size: 28rpx;
		color: #333;
		flex-shrink: 0;
	}
	
	.row-content {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}
	
	.amount-input {
		text-align: right;
		font-size: 40rpx;
		font-weight: bold;
		color: #f0ad4e;
		width: 100%;
		border: none;
		outline: none;
		background: transparent;
	}
	
	.type-selector {
		display: flex;
		border: 1rpx solid #f0ad4e;
		border-radius: 8rpx;
		overflow: hidden;
	}
	
	.type-item {
		flex: 1;
		text-align: center;
		padding: 8rpx 15rpx;
		background-color: #fff;
		color: #999;
		font-size: 28rpx;
	}
	
	.type-item.active {
		background-color: #f0ad4e;
		color: #fff;
	}
	
	.desc-input {
		text-align: right;
		width: 100%;
		font-size: 28rpx;
		border: none;
		outline: none;
		background: transparent;
	}
	
	.item-text {
		font-size: 26rpx;
		color: #999;
		text-align: right;
	}
	
	.save-section {
		padding: 8rpx 15rpx;
		min-height: 50rpx;
	}
	
	.save-btn {
		background-color: #f0ad4e;
		color: white;
		border: none;
		border-radius: 8rpx;
		font-size: 28rpx;
		padding: 8rpx;
		width: 100%;
		height: 75rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	/* 弹窗样式 */
	.popup-container {
		background-color: #fff;
		border-top-left-radius: 16rpx;
		border-top-right-radius: 16rpx;
		padding: 15rpx;
		max-height: 50vh;
	}
	
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 15rpx;
	}
	
	.popup-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
	}
	
	.popup-close {
		color: #f0ad4e;
		font-size: 26rpx;
	}
	
	.category-list {
		max-height: 300rpx;
	}
	
	.category-item {
		padding: 20rpx 15rpx;
		font-size: 28rpx;
	}
	
	.category-item:last-child {
	}
	
	.empty-state {
		text-align: center;
		padding: 30rpx 15rpx;
		color: #999;
		font-size: 26rpx;
	}
	
	.date-picker-container {
		padding: 15rpx 0;
	}
	
	.date-picker {
		height: 250rpx;
	}
	
	.picker-item {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 60rpx;
		font-size: 28rpx;
	}
	
	.confirm-btn-container {
		padding: 15rpx 0;
	}
	
	.confirm-btn {
		background-color: #f0ad4e;
		color: white;
		border: none;
		border-radius: 8rpx;
		font-size: 28rpx;
		padding: 8rpx;
		width: 100%;
		height: 50rpx;
	}
</style>